import React, {useEffect, useState} from 'react';
import {request} from "../../../utils/requset";
import {Alert, Modal, Pagination, Spin, Table, message, Empty, Button} from "antd";


const UploadRecord = () => {

    const [loading, setLoading] = useState(false);
    const [modalContent, setModalContent] = useState('');
    // const [pageInfo, setPageInfo] = useState({
    //     pageNum:1,
    //     pageSize:10
    // });
    const [pageNum, setPageNum] = useState(1);
    const [pageSize, setPageSize] = useState(10);
    const [total, setTotal] = useState(0);

    // 计算当前页显示的条数
    let startRow = (pageNum - 1) * pageSize + 1;
    let endRow = Math.min(pageNum * pageSize, total);
    // 页码变化时
    const onPageChange = (page, size) => {
        // 设置分页相关的状态
        setPageNum(page)
        setPageSize(size)
        startRow = (pageNum - 1) * pageSize + 1;
        endRow = Math.min(pageNum * pageSize, total)
    };

    const [error, setError] = useState(false);
    const [dataSource, setDataSource] = useState([]);
    const [selectedRowKeys, setSelectedRowKeys] = useState([]); // 选中行的状态
    const [visible, setVisible] = useState(false);
    const handleCancel = () => {
        setVisible(false);
    };

    const [tableHeight, setTableHeight] = useState(500); // 默认高度
    // 动态设置表格高度
    useEffect(() => {
        const updateTableHeight = () => {
            const viewportHeight = window.innerHeight;
            const desiredHeight = viewportHeight - 535.99; // 例如，减去200像素用于其他内容
            setTableHeight(desiredHeight > 200 ? desiredHeight : 200); // 设置最小高度为300
        };

        updateTableHeight();
        window.addEventListener('resize', updateTableHeight);
        return () => window.removeEventListener('resize', updateTableHeight);
    }, []);

    const [searchParams, setSearchParams] = useState({
        year: '',
        kjqj: '',
        pzbh: '',
        zy: '',
        kmbh: '',
        je: '',
        xmbh: ''
    });

    const uploadRecordColumns = [
        {
            title: 'id',
            dataIndex: 'id',
            key: 'id',
            hidden: true
        },
        {
            title: '文件名称',
            dataIndex: 'filename',
            key: 'filename',
            width: 150,
        },
        {
            title: '文件类型',
            dataIndex: 'file_content_type_name',
            key: 'file_content_type_name',
            width: 150,
        },
        {
            title: '上传时间',
            dataIndex: 'upload_time',
            key: 'upload_time',
            width: 260,
        },
        {
            title: '最后加载数据时间',
            dataIndex: 'analyse_time',
            key: 'analyse_time',
            width: 260,
        },
        {
            title: '操作',
            dataIndex: 'file_url',
            key: 'file_url',
            width: 200,
            align: 'center',
            render: (text, record) => (
                <div style={{ display: 'flex', justifyContent: 'space-between' }}>
                    <Button type={'primary'} onClick={() => handleReAnalyseData(record.id)}>重新加载</Button>
                    <Button type={'primary'} onClick={() => handleDownload(record.id, record.filename)}>下载</Button>
                </div>
            ),
        },

    ];

    const handleReAnalyseData = async (id)=>{
        setLoading(true);
        try {
            const response = await request.post('/file_upload/api/load_content_data',  {
                fileid:id
            });

            const data = response.data;
            // console.log(data)
            // console.log(data ? data.code : 500)
            if (data && data.code === 200) {
                message.success('数据加载完成！');
                await fetchData();
            } else if (data && data.message) {
                message.error(data.message);
            }
        } catch (error) {
            if (error.response) {
                message.error(`数据加载失败: ${error.response.data.message}`);
            } else {
                // console.error(':', error);
                message.error('数据加载失败');
            }
        } finally {
            setLoading(false);
        }
    }
    const handleDownload = async (id, filename) => {
        // console.log(id)
        setLoading(true);
        try {
            // const response = await fetch(`/file_upload/api/download_record/${file_url}`, {
            //     method: 'GET',
            //     headers: {
            //       'Content-Type': 'application/json',
            //     },
            //   });
            const payload = {
                fileid:id
            }

            const response = await request.post('/file_upload/api/download_record', payload, {
                responseType: 'blob' // 设置响应类型为 blob，以便处理文件下载
            });
            // 从响应头中提取文件名
            const contentDisposition = response.headers['content-disposition'];
            const fileName = filename || (contentDisposition
            ? contentDisposition.split('filename=')[1].replace(/"/g, '') // 解析文件名
            : 'downloaded_file.xlsx');  // 默认文件名

            // 创建一个链接并模拟点击下载 Excel 文件
            const url = window.URL.createObjectURL(new Blob([response.data]));
            const link = document.createElement('a');
            link.href = url;
            link.setAttribute('download', fileName);  // 文件名
            document.body.appendChild(link);

            // 自动点击链接开始下载
            link.click();

            // 下载后清理
            link.parentNode.removeChild(link);
            message.success('文件下载完成！');
        } catch (error) {
            if (error.response) {
                message.error(`文件下载失败: ${error.response.data.message}`);
            } else {
                // console.error(':', error);
                message.error('文件下载失败');
            }
        } finally {
            setLoading(false);
        }
    };

    // 在组件挂载时获取数据
    useEffect(() => {
        fetchData();
    }, [pageNum, pageSize, searchParams]);


    // 获取表格数据的函数
    const fetchData = async () => {
        setLoading(true);
        setError(null);
        try {
            // console.log(values)
            // console.log(currentPage)
            // 替换为你的实际 API URL
            const response = await request.post('/file_upload/api/pagedata', {
                    "pageNum": pageNum,
                    "pageSize": pageSize
                }
            );

            const jsonData = response.data;
            // console.log(jsonData)
            // // 设置分页相关的状态
            // setPageInfo({
            //     pageNum: jsonData.pageNum,
            //     pageSize: jsonData.pageSize,
            // })
            setPageNum(jsonData.pageNum)
            setPageSize(jsonData.pageSize)
            setTotal(jsonData.total)
            // 设置表格数据源
            setDataSource(jsonData.data);
        } catch (err) {
            console.error('数据获取失败:', err);
            setError('数据获取失败，请稍后再试。');
        } finally {
            setLoading(false);
        }
    };


    return (

        <div className="my-data-table-container">
            {/*<Title level={4}>数据上传记录明细</Title>*/}
            {error && <Alert message={error} type="error" showIcon style={{marginBottom: 16}}/>}

            <Spin spinning={loading}>
                <Table
                    columns={uploadRecordColumns}
                    dataSource={dataSource}
                    rowKey="id"
                    pagination={false} // 使用自定义的分页组件
                    scroll={{x: 'max-content', y: `max(calc(100vh - 574.14px), 200px)`}} // 启用水平和垂直滚动
                    rowClassName={(record) =>
                        selectedRowKeys.includes(record.code) ? 'selected-row' : ''
                    }
                    locale={{emptyText: <Empty description="未找到数据"></Empty>}}
                />
                <Modal
                    title="数据描述"
                    open={visible}
                    onCancel={handleCancel}
                    footer={null}
                >
                    <p>{modalContent}</p>
                </Modal>
            </Spin>
            <div>
                                <span>
                                    当前 {startRow}-{endRow} 条，共 {total} 条
                                </span>
                <Pagination
                    current={pageNum}
                    pageSize={pageSize}
                    total={total}
                    showSizeChanger
                    pageSizeOptions={['10', '20', '50', '100']} // 限制每页条目数选项
                    style={{marginTop: 16, textAlign: 'right'}}
                    onChange={onPageChange}      // 页码变化时触发
                />
            </div>
        </div>
    );
}

export default UploadRecord;